package com.ming.mallchat.common.common.event.listener;

import com.ming.mallchat.common.common.event.UserBlackEvent;
import com.ming.mallchat.common.common.event.UserOnlineEvent;
import com.ming.mallchat.common.user.cache.UserCache;
import com.ming.mallchat.common.user.dao.UserDao;
import com.ming.mallchat.common.user.domain.enums.UserActiveStatusEnum;
import com.ming.mallchat.common.user.pojo.User;
import com.ming.mallchat.common.user.service.IpService;
import com.ming.mallchat.common.websocket.domain.adapter.WebSocketAdapter;
import com.ming.mallchat.common.websocket.domain.service.WebSocketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

@Component
public class UserBlackListener {

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserCache userCache;

    @Autowired
    private WebSocketService webSocketService;


    /**
     * 发送该用户被拉黑的消息
     * @param event 拉黑用户事件
     */
    @Async
    @TransactionalEventListener(classes = UserBlackEvent.class,phase = TransactionPhase.AFTER_COMMIT)
    public void sendMsg(UserBlackEvent event){
        User user = event.getUser();
        webSocketService.sendMsgToAll(WebSocketAdapter.buildBlack(user));
    }

    /**
     * 更新用户状态
     * @param event 拉黑用户事件
     */
    @Async
    @TransactionalEventListener(classes = UserBlackEvent.class,phase = TransactionPhase.AFTER_COMMIT)
    public void changeUserStatus(UserBlackEvent event){
        userDao.invalidUid(event.getUser().getId());
    }


    /**
     * 删除黑名单缓存
     * @param event 拉黑用户事件
     */
    @Async
    @TransactionalEventListener(classes = UserBlackEvent.class,phase = TransactionPhase.AFTER_COMMIT)
    public void refreshRedis(UserBlackEvent event){
        userCache.evictBlackMap();
    }

}
